package com.eras.shoes.utils


object HexConverter {
    private const val HEX_CHARS = "0123456789ABCDEF"

    // 中文转16进制字节数组（UTF-8编码）
    fun chineseToHexBytes(input: String): ByteArray {
        val bytes = input.toByteArray(Charsets.UTF_8)
        val result = ByteArray(bytes.size * 2)
        var index = 0

        bytes.forEach { byte ->
            val value = byte.toInt() and 0xFF
            result[index++] = HEX_CHARS[value shr 4].toByte()
            result[index++] = HEX_CHARS[value and 0x0F].toByte()
        }
        return result
    }

    // 16进制字节数组转可读字符串
    fun hexBytesToString(hexBytes: ByteArray): String {
        val byteArray = ByteArray(hexBytes.size / 2)
        for (i in byteArray.indices) {
            val high = HEX_CHARS.indexOf(hexBytes[i * 2].toChar())
            val low = HEX_CHARS.indexOf(hexBytes[i * 2 + 1].toChar())
            byteArray[i] = (high shl 4 or low).toByte()
        }
        return String(byteArray, Charsets.UTF_8)
    }

    fun formatStringLength(input: String): String {
        // 计算长度（两个字符算一位）
        val length = (input.length + 1) / 2
        // 补足20位
        return input.padEnd(40, '0').take(40)
    }

    fun padStringWithZeros(input: String): String {
        return if (input.length < 40) {
            input.padStart(40, '0')
        } else {
            input
        }
    }


    fun formatStringWithPadding(input: String): String {
        // 计算实际长度（两个字符算一位）
        val actualLength = (input.length + 1) / 2
        // 计算需要补0的数量
        val paddingZeros = maxOf(0, 20 - actualLength)
        // 生成补0字符串并拼接原字符串
        return "0".repeat(paddingZeros) + input
    }
    fun splitStringByTwoChars(input: String): List<String> {
        require(input.length == 40) { "输入字符串长度必须为40" }

        return (0 until 20).map { index ->
            input.substring(index * 2, (index + 1) * 2)
        }
    }

    fun concatWith0x(input: String): String {
        return input.chunked(2).joinToString("") { "0x$it" }
    }

    fun hexStringToBytes(hexString: String): ByteArray {
        require(hexString.length % 2 == 0) { "输入字符串长度必须是偶数" }

        return hexString.chunked(2).map {
            "0x$it".toInt(16).toByte()
        }.toByteArray()
    }

    fun convertHexString(hexStr: String): List<String> {
        require(hexStr.length % 2 == 0) { "输入字符串长度必须是偶数" }

        return hexStr.chunked(2).map {
            "0x$it".uppercase()
        }
    }

    fun hexStringToByte(hexStr: String): Byte {
        require(hexStr.startsWith("0x") || hexStr.startsWith("0X")) {
            "输入字符串必须以0x或0X开头"
        }
        return hexStr.substring(2).toInt(16).toByte()
    }

}
